package com.nuanshui.heatedloan.extension.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

/**
 * 验证码表单认证过滤器
 * 
 */
public class CaptchaFormAuthenticationFilter extends FormAuthenticationFilter {

	public static final String DEFAULT_CAPTCHA_PARAM = "captcha";
	private final String captchaParam = DEFAULT_CAPTCHA_PARAM;

	public String getCaptchaParam() {
		return captchaParam;
	}

	protected String getCaptcha(final ServletRequest request) {
		return WebUtils.getCleanParam(request, getCaptchaParam());
	}

	@Override
	protected AuthenticationToken createToken(final ServletRequest request,
			final ServletResponse response) {
		final String username = getUsername(request);
		final String password = getPassword(request);
		final String captcha = getCaptcha(request);
		final boolean rememberMe = isRememberMe(request);
		final String host = getHost(request);

		return new CaptchaUsernamePasswordToken(username, password, rememberMe,
				host, captcha);
	}

	/**
	 * 覆盖默认实现，用sendRedirect直接跳出框架，以免造成js框架重复加载js出错。
	 */
	@Override
	protected boolean onLoginSuccess(final AuthenticationToken token,
			final Subject subject, final ServletRequest request,
			final ServletResponse response) throws Exception {
		final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest
				.getHeader("X-Requested-With"))
				|| (request.getParameter("ajax") == null)) {
			httpServletResponse.sendRedirect(httpServletRequest
					.getContextPath() + this.getSuccessUrl());
		} else {
			httpServletRequest.getRequestDispatcher(
					"/cms/manage/login/timeout/success").forward(
					httpServletRequest, httpServletResponse);
		}

		return false;
	}

}
